// import { fileURLToPath, URL } from "node:url";
let path = require("path");
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import postCssPxToRem from "postcss-pxtorem";

import autoprefixer from "autoprefixer";
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");
  return {
    base: "./",
    build: {
      minify: "terser",
      terserOptions: {
        // 清除console和debugger
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      outDir: "dist",
      assetsDir: "static",
      chunkSizeWarningLimit: 1000,
      rollupOptions: {
        output: {
          // 分包
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
        },
      },
    },
    plugins: [
      vue(),
      createSvgIconsPlugin({
        // Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), "src/assets/icons/svg")],
        // Specify symbolId format
        symbolId: "icon-[dir]-[name]",
        svgoOptions: {
          plugins: [
            {
              name: "removeAttrs",
              params: { attrs: ["class", "data-name", "fill", "stroke"] },
            },
          ],
        },
      }),
    ],

    resolve: {
      alias: {
        "@": path.resolve("./src"),
        "@http": path.resolve("./src/utils/request.ts"),
      },
      extensions: [".js", ".ts", ".json", ".vue"], // 导入时想要省略的扩展名列表
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: "@import './src/assets/styles/var.scss';",
        },
      },
      autoprefixer: {
        overrideBrowserslist: [
          "Android 4.1",
          "iOS 7.1",
          "Chrome > 31",
          "ff > 31",
          "ie >= 8",
          "last 10 versions", // 所有主流浏览器最近10版本用
        ],
        grid: true,
      },
      postcss: {
        plugins: [
          autoprefixer({
            overrideBrowserslist: [
              "Android 4.1",
              "iOS 7.1",
              "Chrome > 31",
              "ff > 31",
              "ie >= 8",
            ],
          }),
          postCssPxToRem({
            // 自适应，px>rem转换
            rootValue: 192, // 75表示750设计稿，37.5表示375设计稿
            propList: ["*"], // 需要转换的属性，这里选择全部都进行转换
            selectorBlackList: ["norem"], // 过滤掉norem-开头的class，不进行rem转换
          }),
        ],
      },
    },
    server: {
      proxy: {
        [env.VITE_APP_BASE_URL]: {
          target: "http://localhost:8080",
          changeOrigin: true,
          rewrite: (path) => path.replace(env.VITE_APP_BASE_URL, ""),
        },
      },
    },
  };
});
